<template>
  <!--审核师生互选-->
  <div class="review-teacher-stu">
    <InnerBreadcrumb v-if="!idTip"  v-model="indexKey" :path="breadPath" :showBack="true" />
    <div class="edu-page-warp" v-show="indexKey === 'MAIN'">
      <!--查看老师/学生信息 弹框-->
      <TeacherStuDialog :dialogVisible="dialogVisible" :teacherStuForm="teacherStuForm" :viewType="viewType" @teacher-stu-close="teacherStuClose"></TeacherStuDialog>

      <!--批量驳回 弹框-->
      <edu-dialog :title="$t('graduationDesign.batchReject')" width="45%" @close="onRejectClose" :visible="rejectDialogVisible">
        <el-form :model="rejectForm" :rules="rejectRules" ref="rejectForm" label-position="right" label-width="100px" label-suffix="：">
          <el-form-item :label="$t('graduationDesign.reviewOpioion')" prop="content">
            <el-input v-model="rejectForm.content" type="textarea" :rows="4" maxlength="100" class="search-item" show-word-limit :placeholder="$t('graduationDesign.pleaseEnter')"></el-input>
          </el-form-item>
        </el-form>
        <div slot="buttons">
          <el-button @click="onRejectClose">{{$t('graduationDesign.cancel')}}</el-button>
          <el-button type="danger" @click="onRejectSubmit">{{$t('graduationDesign.reject')}}</el-button>
        </div>
      </edu-dialog>

      <condition-card @reset="reset" @search="searchList" label-width="140px">
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.graduationYear')">
              <el-date-picker class="search-item" :clearable="false" v-model="queryForm.grade" @change="handleGradeChange" value-format="yyyy" type="year" :placeholder="$t('graduationDesign.pleaseChoose')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.subjectCollege')">
              <el-select v-model="queryForm.collegeId" filterable @change="handleCollegeChange" class="search-item" clearable>
                <el-option v-for="item in source.collegeOptions" :key="item.collegeId" :label="item.collegeIdI18n" :value="item.collegeId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.subjectMajor')">
              <el-select v-model="queryForm.subjectId" filterable class="search-item" clearable>
                <el-option v-for="item in source.subjectOptions" :key="item.subjectId" :label="item.subjectName" :value="item.subjectId" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.subjectType')">
              <el-select v-model="queryForm.projectType" filterable class="search-item" clearable>
                <el-option v-for="item in source.subjectTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.subjectNature')">
              <el-select v-model="queryForm.projectNatureId" filterable class="search-item" clearable>
                <el-option v-for="item in source.subjectNatureOptions" :key="item.id" :label="item.subjectProperties" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.subjectSource')">
              <el-select v-model="queryForm.projectSourceId" filterable class="search-item" clearable>
                <el-option v-for="item in source.subjectSourceOptions" :key="item.id" :label="item.subjectSource" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.subjectName')">
              <el-input v-model="queryForm.projectName" class="search-item" :placeholder="$t('graduationDesign.pleaseEnter')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.reviewStatus')">
              <el-select v-model="queryForm.collStatus" filterable class="search-item" clearable>
                <el-option v-for="item in source.statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.declarer')">
              <el-input v-model="queryForm.teacherName" class="search-item" :placeholder="$t('graduationDesign.pleaseEnter')"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
      <el-card shadow="never">
        <div class="edu-page-title">{{$t('graduationDesign.reviewTeacherStudentSelect')}}</div>
        <div class="edu-opertion-bar">
          <div class="float-left">
            <el-input v-model="queryForm.studentName" :placeholder="$t('graduationDesign.pleaseEnterStuSearch')" style="width:300px" @keyup.enter.native="searchList" clearable>
              <i slot="suffix" class="el-icon-search" style="margin-top:10px;cursor:pointer" @click="searchList"></i>
            </el-input>
          </div>
          <div class="float-right">
            <el-button @click="onExport" v-loading.fullscreen.lock="loading" element-loading-text="Loading" element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, .48)">{{$t('graduationDesign.export')}}</el-button>
            <el-button type="danger" @click="onBatchReject">{{$t('graduationDesign.reject')}}</el-button>
            <el-button type="primary" @click="onBatchPass">{{$t('graduationDesign.pass')}}</el-button>
          </div>
        </div>

        <edu-table ref="reviewTeacherStuTable" :url="getList" @selection-change="handleSelectChange">
          <edu-table-column :label="$t('graduationDesign.graduationYear')" prop="grade" min-width="90" ></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.subjectName')" prop="projectName" min-width="200"></edu-table-column>
          <edu-table-column label="副标题" prop="subtitleName" min-width="140" ></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.subjectNature')" prop="projectNature" min-width="80"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.subjectSource')" prop="projectSource" min-width="80"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.subjectType')" prop="projectType" min-width="90"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.subjectCollege')" prop="collegeIdI18n" min-width="120"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.subjectMajor')" prop="subjectIdI18n" min-width="120"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.subjectDerection')" prop="direction" min-width="120"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.student')" prop="studentName" min-width="130">
            <template slot-scope="scope">
              <el-button type="text" @click="onDetail(scope.row, 'STU')">{{`${scope.row.studentName}(${scope.row.studentId})`}}</el-button>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('graduationDesign.declarer')" prop="applicantName" min-width="130">
            <template slot-scope="scope">
              <el-button type="text" @click="onDetail(scope.row, 'TEACHER')">{{`${scope.row.teacherName}(${scope.row.teacherId})`}}</el-button>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('graduationDesign.submitTime')" prop="submitTime" min-width="100"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.reviewStatus')" min-width="90" fixed="right">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.collStatus === 'WaitCommit'" type="info">{{$t('graduationDesign.draft')}}</el-tag>
              <el-tag v-else-if="scope.row.collStatus === 'Process'" type="info">{{$t('graduationDesign.pendingReview')}}</el-tag>
              <el-tag v-else-if="scope.row.collStatus === 'Checking'" type="info">{{$t('graduationDesign.underReview')}}</el-tag>
              <el-tag v-else-if="scope.row.collStatus === 'Reject'" type="danger">{{$t('graduationDesign.rejected')}}</el-tag>
              <el-tag v-else-if="scope.row.collStatus === 'End'" type="success">{{$t('graduationDesign.passed')}}</el-tag>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('graduationDesign.operation')" min-width="150" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="onReview(scope.row)" v-if="scope.row.collStatus === 'Checking'">{{$t('graduationDesign.review')}}</el-button>
              <el-button type="text" @click="onView(scope.row)">{{$t('graduationDesign.view')}}</el-button>
              <!-- <el-button type="text" @click="onDelete(scope.row)" v-if="scope.row.collStatus === 'End'">删除</el-button> -->
            </template>
          </edu-table-column>
        </edu-table>
      </el-card>
    </div>
<!-- ||indexKey='DETAIL' -->
    <div v-if="indexKey === 'REVIEW' || indexKey === 'VIEW'||indexKey==='DETAIL'">
      <!--审核/查看-->
      <TopicInfo :actionType="actionType" :basicInfoForm="basicInfoForm" :progressData="progressData" @topic-reject="topicReject" @topic-pass="topicPass" @topic-cancel="topicCancel" :idTip="idTip" :fromCheckDetail="fromCheckDetail"></TopicInfo>
    </div>
  </div>
</template>
<script>
import API from "common/src/api/underGraduationDesign/reviewSubject"
import tools from 'common/src/views/underGraduationDesign/tools.js';
export default {
  name: 'reviewSubjectDesignated',
  props: {
    dataInfo: {
      type: Object,
      default: {}
    },
    idTip:{
      type: String,
      default:""
    },
    fromCheckDetail:{
      type: Boolean,
      required: false
    },
  },
  data() {
    return {
      api: API,
      getList: '/api/designservice/optChooseEachCheck/queryByPage',
      queryForm: {
        grade: '',
        collegeId: '',
        subjectId: '',
        projectType: '',
        projectNatureId: '',
        projectSourceId: '',
        projectName: '',
        applicantName: '',
        collStatus: '',
        activeAuthId: localStorage.getItem("activeAuthId")
      },
      loading: false,
      indexKey: 'MAIN',
      source: {
        collegeOptions: [], // 学院
        subjectOptions: [], // 专业
        // 课题类型
        subjectTypeOptions: [{
          label: "毕业论文",
          value: "毕业论文",
        }, {
          label: "毕业设计",
          value: "毕业设计",
        }],
        subjectNatureOptions: [], // 课题性质
        subjectSourceOptions: [], // 课题来源
        // 审核状态
        statusOptions: [{
          label: "待审核",
          value: "Process"
        }, {
          label: "审核中",
          value: "Checking"
        }, {
          label: "已驳回",
          value: "Reject"
        }, {
          label: "已通过",
          value: "End"
        }]
      },
      breadPath: {
        label: this.$t('graduationDesign.reviewTeacherStudentSelect'),
        key: "MAIN",
        children: [
          {
            key: "VIEW",
            label: this.$t('graduationDesign.viewSubject')
          },
          {
            key: "REVIEW",
            label: this.$t('graduationDesign.reviewTopic')
          }
        ]
      },
      selectedData: [], // 勾选的列表数据
      actionType: "",
      // 批量驳回
      rejectDialogVisible: false,
      rejectForm: {},
      rejectRules: {
        content: [
          { required: true, message: this.$t('graduationDesign.pleaseEnter'), trigger: "blur" }
        ]
      },
      basicInfoForm: {},
      progressData: [], //审核进度列表
      dialogVisible: false,
      teacherStuForm: {}, // 查看老师/学生信息表单
      viewType: ''
    };
  },
  created() {
    this.queryForm.grade = new Date().getFullYear() + '';
    this.getCollege();
    this.getSubjectSource();
    this.getSubjectNature();
  },
  mounted() {
    if(this.dataInfo&&this.dataInfo.no){
      console.log(this.dataInfo,'ppp')
      this.indexKey=this.$route.query.indexKey;
      this.actionType=this.$route.query.actionType;
      if(this.indexKey=='DETAIL'){
        this.actionType='VIEW_TUTOR'
      }else{
        this.actionType = "REVIEW_STU";
      }
      this.basicInfoForm=this.dataInfo.content;
      this.progressData=this.dataInfo.listApproveHistory;
    }else{
      this.searchList();
    }
  },
  methods: {
    searchList() {
      this.$refs.reviewTeacherStuTable.search(this.queryForm);
    },
    reset() {
      this.queryForm = {
        grade: '',
        collegeId: '',
        subjectId: '',
        projectType: '',
        projectNatureId: '',
        projectSourceId: '',
        projectName: '',
        applicantName: '',
        collStatus: '',
        activeAuthId: localStorage.getItem("activeAuthId")
      };
      this.source.subjectOptions = [];
      this.queryForm.grade = new Date().getFullYear() + '';
      this.getSubjectSource();
      this.getSubjectNature();
      this.searchList();
    },
    handleSelectChange(val) {
      this.selectedData = val;
    },
    handleGradeChange(val) {
      this.queryForm.subjectId = "";
      this.source.subjectOptions = [];
      if (val && this.queryForm.collegeId) {
        this.handleCollegeChange(this.queryForm.collegeId);
      }
      this.getSubjectSource();
      this.getSubjectNature();
    },
    // 查学院
    getCollege() {
      this.api.getCollege().then(res => {
        this.source.collegeOptions = res;
      });
    },
    // 选择毕业年份和学院查专业
    handleCollegeChange(val) {
      this.queryForm.subjectId = "";
      this.source.subjectOptions = [];
      if (val && this.queryForm.grade) {
        const params = {
          grade: this.queryForm.grade,
          college: val
        };
        this.api.getSubject(params).then(res => {
          this.source.subjectOptions = res.data;
        }).catch();
      }
    },
    // 查课题来源
    getSubjectSource() {
      const params = {
        year: this.queryForm.grade
      };
      this.api.getSource(params).then(res => {
        this.source.subjectSourceOptions = res.data;
      }).catch();
    },
    // 查课题性质
    getSubjectNature() {
      const params = {
        year: this.queryForm.grade
      };
      this.api.getNature(params).then(res => {
        this.source.subjectNatureOptions = res.data;
      }).catch();
    },
    // 审核
    onReview(row) {
      this.actionType = "REVIEW_TOPIC";
      const params = {
        studentId: row.studentId,
        infoId: row.id,
        infoType: row.infoType
      };
      this.api.getSubjectDetail(params).then(({ data }) => {
        this.indexKey = 'REVIEW';
        this.basicInfoForm = { ...data.applicationTeacherEntity };
        this.basicInfoForm.grade = row.grade ? row.grade + '' : '';
        this.basicInfoForm.flowNo = row.flowNo;
        this.basicInfoForm.stuCollegeI18n = data.stuCollegeI18n;
        this.basicInfoForm.stuSubjectIdI18n = data.stuSubjectIdI18n;
        this.basicInfoForm.applicantName = row.teacherName;
        this.basicInfoForm.teacherName = row.teacherName;
        this.basicInfoForm.studentName = row.studentName;
        this.progressData = [];
        if (row.flowNo) {
          this.getReviewProgress(row.flowNo);
        }
      }).catch();
    },
    // 查审核进度
    getReviewProgress(applyNo) {
      this.api.getProgress(applyNo).then(res => {
        this.progressData = res.data.listApproveHistory;
      }).catch();
    },
    // 单条审核驳回("2")
    topicReject(data) {
      if(this.dataInfo&&this.dataInfo.no){
        var no=this.dataInfo.no;
      }
      const params = {
        no: data.basicInfoForm.flowNo?data.basicInfoForm.flowNo:no,
        type: "2",
        content: data.content,
        grade: data.basicInfoForm.grade
      };
      this.handleSubmit(params, "Reject");
    },
    // 单条审核通过("1")
    topicPass(data) {
      if(this.dataInfo&&this.dataInfo.no){
        var no=this.dataInfo.no;
      }
      const params = {
        no: data.basicInfoForm.flowNo?data.basicInfoForm.flowNo:no,
        type: "1",
        grade: data.basicInfoForm.grade
      };
      this.handleSubmit(params, "End");
    },
    // 审核取消
    topicCancel() {
      this.indexKey = 'MAIN';
      this.searchList();
    },
    // 查看
    onView(row) {
      this.actionType = "REVIEW_TOPIC_VIEW";
      const params = {
        studentId: row.studentId,
        infoId: row.id,
        infoType: row.infoType
      };
      this.api.getSubjectDetail(params).then(({ data }) => {
        this.indexKey = 'VIEW';
        this.basicInfoForm = { ...data.applicationTeacherEntity };
        this.basicInfoForm.grade = row.grade ? row.grade + '' : '';
        this.basicInfoForm.flowNo = row.flowNo;
        this.basicInfoForm.stuCollegeI18n = data.stuCollegeI18n;
        this.basicInfoForm.stuSubjectIdI18n = data.stuSubjectIdI18n;
        this.basicInfoForm.applicantName = row.teacherName;
        this.basicInfoForm.teacherName = row.teacherName;
        this.basicInfoForm.studentName = row.studentName;
        this.progressData = [];
        if (row.flowNo) {
          this.getReviewProgress(row.flowNo);
        }
      }).catch();
    },
    onDelete(row) {
      this.$delConfirm("您确定要删除吗？", "删除").then(() => {
        const params = {
          id: row.infoId
        };
        this.api.teacherStuDelete(params).then(res => {
          this.$message.success("删除成功");
          this.searchList();
        }).catch();
      }).catch(() => { });
    },
    // 批量通过
    onBatchPass() {
      if (this.selectedData.length === 0) {
        this.$eduAlert(this.$t('graduationDesign.pleaseSelectData'), this.$t('graduationDesign.prompt'));
        return false;
      }
      if (!this.validateBatchReview(this.selectedData)) {
        this.$eduAlert(this.$t('graduationDesign.pleaseSelectCheckingData'), this.$t('graduationDesign.prompt'));
        return false;
      }
      this.$eduConfirm(this.$t('graduationDesign.passConfirmTips'), this.$t('graduationDesign.prompt')).then(() => {
        let flowNoList = [];
        const projectIds = [];
        this.selectedData.forEach(item => {
          flowNoList.push(item.flowNo);
          projectIds.push(item.id);
        });
        const params = {
          idList: flowNoList,
          projectIds: projectIds,
          type: "1",
          grade: this.selectedData[0].grade
        };
        this.handleSubmit(params, "batchEnd");
      });
    },
    validateBatchReview(data) {
      let isValid = true;
      for (let index = 0; index < data.length; index++) {
        const item = data[index];
        if (item.collStatus !== 'Checking') {
          isValid = false;
          break;
        }
      }
      return isValid;
    },
    // 批量驳回
    onBatchReject() {
      if (this.selectedData.length === 0) {
        this.$eduAlert(this.$t('graduationDesign.pleaseSelectData'), this.$t('graduationDesign.prompt'));
        return false;
      }
      if (!this.validateBatchReview(this.selectedData)) {
        this.$eduAlert(this.$t('graduationDesign.pleaseSelectCheckingData'), this.$t('graduationDesign.prompt'));
        return false;
      }
      this.rejectForm = {};
      this.rejectDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.rejectForm.clearValidate();
      });
    },
    onRejectClose() {
      this.rejectDialogVisible = false;
    },
    // 批量驳回提交
    onRejectSubmit() {
      this.$refs.rejectForm.validate(valid => {
        if (valid) {
          let flowNoList = [];
          const projectIds = [];
          this.selectedData.forEach(item => {
            flowNoList.push(item.flowNo);
            projectIds.push(item.id);
          });
          const params = {
            idList: flowNoList,
            projectIds: projectIds,
            content: this.rejectForm.content,
            type: "2",
            grade: this.selectedData[0].grade
          };
          this.handleSubmit(params, "batchReject");
        } else {
          return false;
        }
      });
    },
    // 处理通过、驳回（批量）请求
    handleSubmit(data, actionMode) {
      let reqApi = null;
      if (actionMode === "batchEnd" || actionMode === "batchReject") {
        reqApi = this.api.teacherStuBatchApproval(data);
      } else {
        reqApi = this.api.teacherStuApproval(data);
      }
      reqApi.then(res => {
        this.$message.success((actionMode === "End" || actionMode === "batchEnd") ? this.$t('graduationDesign.passed') : this.$t('graduationDesign.rejected'));
        if (actionMode === "End" || actionMode === "Reject") {

           if(this.dataInfo&&this.dataInfo.no){
              this.$router.go(-1);
            }else{
               // 单条审核返回主页面
              this.indexKey = "MAIN";
            }
        } else if (actionMode === "batchReject") {
          // 关闭批量驳回弹框
          this.rejectDialogVisible = false;
        }
        if(this.dataInfo&&this.dataInfo.no){
        }else{
           this.searchList();
        }
      }).catch(() => { });
    },
    // 查看老师/学生信息
    onDetail(row, type) {
      this.viewType = type;
      let reqApi = null;
      if (type === "STU") {
        reqApi = this.api.getStuInfo(row.studentId);
      } else {
        reqApi = this.api.getTeacherInfo(row.teacherId);
      }
      reqApi.then(res => {
        this.dialogVisible = true;
        this.teacherStuForm = { ...res.data };
        if (type === "STU") {
          this.teacherStuForm.teacherName = `${row.teacherName}(${row.teacherId})`;
        }
      });
    },
    // 返回
    teacherStuClose() {
      this.dialogVisible = false;
    },
    // 导出
    onExport() {
      const params = Object.assign(this.queryForm, { exprotList: this.selectedData });
      this.api.teacherStuExport(params).then(res => {
        if (res.code == 200) {
          // this.delayRequest(res.data.key);
          tools.downloadFile(res.data.key, "审核师生互选.xls", null, this, true);
        }
      });
    },
    // 查文件导出状态，等待导出
    async delayRequest(key) {
      this.loading = true;
      await new Promise(resolve => setTimeout(resolve, 3000));
      this.api.getExportStatus(key).then(res => {
        this.loading = false;
        if (res.code === 200 && res.data.status) {
          let path = 'api/designservice/common/export?path=' + res.data.path;
          window.open(path);
        } else {
          this.delayRequest(key);
        }
      }).catch(err => {
        this.loading = false;
        this.delayRequest(key);
      });
    }
  },
  components: {
    TopicInfo: () => import('../components/topicInfo'),
    TeacherStuDialog: () => import('../components/teacherStuDialog')
  }
}
</script>
<style lang="scss" scoped>
.review-teacher-stu {
    .search-item {
        width: 100%;
    }
}
</style>
